package cn.kgc.springcloud.web.controller;

import cn.hutool.core.util.IdUtil;
import cn.kgc.springcloud.web.entity.Clazz;
import cn.kgc.springcloud.web.form.ClazzForm;
import cn.kgc.springcloud.web.response.ResponseResult;
import cn.kgc.springcloud.web.service.ClazzService;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author 课工场
 * @date 2024/7/29
 * @description
 */
@RestController
@RequestMapping("clazz")
public class ClazzController {

    @Resource
    private ClazzService clazzService;

    @GetMapping("list")
    public ResponseResult clazzList(){
        return  clazzService.ClazzList();
    }

    @GetMapping("{id}")
    public Clazz getOneClazz(@PathVariable("id") Integer id){

        return  clazzService.getById(id);
    }

    @DeleteMapping("{id}")
    public ResponseResult deleteClazz(@PathVariable("id") Integer id){


        // TODO  删除班级的logo
        String path = clazzService.getById(id).getPath();
        File file = new File("D:/upload/" + path);
        if (file.exists()){
            file.delete();
        }

        clazzService.removeById(id);

        return  ResponseResult.success();
    }

    @PostMapping
    public ResponseResult addClazz(ClazzForm clazzForm) throws Exception{

        //  1.文件上传
        MultipartFile file = clazzForm.getFile();
        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String uuid = IdUtil.simpleUUID();
        String lastName = uuid+"."+filenameExtension;
        file.transferTo(new File("D:/upload/"+lastName));

        // 2. 班级信息添加
        Clazz clazz = new Clazz();
        BeanUtils.copyProperties(clazzForm,clazz);
        clazz.setPath(lastName);
        clazzService.save(clazz);

        return  ResponseResult.success().data(clazz);
    }



}
